package com.ghca.storm;

import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Tuple;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by gh on 2016/10/24.
 */
public class WordCountBolt extends BaseRichBolt {


    private Map stormConf;
    private TopologyContext context;
    private OutputCollector collector;
    /**
     * 单词出现的次数
     */
    public static Map<String, Integer> hashMap = new HashMap<String, Integer>();

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) {
        this.stormConf = stormConf;
        this.context = context;
        this.collector = collector;
    }

    public void execute(Tuple input) {
        String word = input.getStringByField("word");
        Integer value = hashMap.get(word);
        if (value == null) {
            hashMap.put(word, 0);
        } else {
            hashMap.put(word, value + 1);
        }

        for (Map.Entry<String, Integer> e : hashMap.entrySet()) {
            System.out.println("输出结果： =============="+e.getKey() + ":" + e.getValue());
        }
    }

    public void declareOutputFields(OutputFieldsDeclarer declarer) {

    }
}
